package me.cabbit.digitone.support;
import java.awt.geom.Point2D;


public class BezierCurve {

	//build a matrix with the berstein coefficents for
	//a cubic bezier (degree 3)
	private static final Matrix bernsteinCoeff 
				= new Matrix(4, 4, new double []
									{ 1,  0,  0, 0,
									 -3,  3,  0, 0,
									  3, -6,  3, 0,
									 -1,  3, -3, 1});
	
	private Matrix px;	
	private Matrix py;

	public BezierCurve() 
	{
		this.px = new Matrix(4, 1, new double[] {0.00, 0.25, 0.75, 1.00});
		this.py = new Matrix(4, 1, new double[] {0.00, 0.25, 0.75, 1.00});
	}
	
	public void setControlPoint(int index, double x, double y)
	{
		this.px.set(index, 0, x);
		this.py.set(index, 0, y);
	}

	public void setControlPoint(int index, Point2D.Double pt)
	{
		setControlPoint(index, pt.x, pt.y);
	}
		
	public Point2D.Double [] interpolate (int segments)
	{
		double step = 1.0 / segments;
		
		Point2D.Double [] points = new Point2D.Double [segments + 1];
		
		double t = 0;
		for (int i = 0; i <= segments; i++)
		{
			Matrix u = new Matrix(1, 4, new double [] {1, t, t*t, t*t*t});
			Matrix preMult = u.multiply(BezierCurve.bernsteinCoeff);
			
			points[i] = new Point2D.Double();
			points[i].x = preMult.multiply(px).get(0, 0);
			points[i].y = preMult.multiply(py).get(0, 0);
	
			t += step;
		}	
		
		return points;
	}
}
